const baseUrl = "https://udev.uxiao.vip/utea"   //测试
// const baseUrl = "https://udian.uxiao.vip/utea" //正式
import store from "@/store/index.js"
// 统一生成请求头
const getHeaders = () => {
	const headers = {
		'Accept': 'application/json',
		'Content-Type': 'application/json',
		'client-type': 'utea_mini'
	}
	const token = uni.getStorageSync("token")
	if (token) headers.Authorization = token
	return headers
}

// 统一处理响应
const handleResponse = (res, resolve, reject) => {
	const {
		statusCode,
		data
	} = res
	if (statusCode === 200) {
		if (data.code !== 10001) {
			resolve(res)
		} else {
			isCode(data)
			reject(new Error('登录状态过期')) // 确保Promise被拒绝
		}
	} else if (statusCode === 401) {
		isCode(data)
		reject(new Error('请求参数错误'))
	} else if (statusCode === 500) {
		showToast('请求异常')
		reject(new Error('服务器错误'))
	} else {
		showToast(`请求失败，状态码：${statusCode}`)
		reject(new Error(`未知错误: ${statusCode}`))
	}
}

// 统一处理失败
const handleFail = (error, reject) => {
	showToast('网络错误')
	reject(error)
}

// 显示提示
const showToast = (title, icon = 'none', duration = 1500, mask = true) => {
	uni.showToast({
		title,
		icon,
		duration,
		mask
	})
}

// 公共请求方法
const request = (method, url, data) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url,
			method,
			data,
			header: getHeaders(),
			timeout: 60000,
			success: (res) => handleResponse(res, resolve, reject),
			fail: (error) => handleFail(error, reject),
			complete: () => uni.hideLoading()
		})
	})
}

// Token失效处理
const isCode = (data) => {
	if (data.code === 10001) {
		uni.clearStorageSync()
		store.state.member = {}
		uni.showModal({
			title: '提示',
			content: '当前登录已过期,请重新登录',
			showCancel: false,
			success: (res) => {
				if (res.confirm) {
					uni.reLaunch({
						url: "/pages/tarbar/home"
					})
				}
			}
		})
		// showToast('当前登录已过期，或者未登录', 'none', 1000)
		// uni.showToast({
		// 	title: '当前登录已过期,请重新登录',
		// 	icon: 'none',
		// 	duration: 1500,
		// 	mask: true,
		// })
		// setTimeout(()=>{
		// 	uni.clearStorageSync()
		// 	store.state.member = {}
		// 	uni.reLaunch({
		// 		url:"/pages/tarbar/home"
		// 	})
		// 	console.log(9999);
		// },1500)

	}
}

// 导出方法
const get = (url, data) => request('GET', url, data)
const post = (url, data) => request('POST', url, data)

export default {
	get,
	post
}